package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.*;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.mapper.UserMapper;
import com.sky.properties.BaiduMapProperties;
import com.sky.properties.MerchantAddress;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.BaiduMapUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: Sabrina
 * @Date:2025/06/15/10:18
 * @Description:
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private BaiduMapUtil baiduMapUtil;
    @Autowired
    private MerchantAddress merchantAddress;
    @Autowired
    private BaiduMapProperties baiduMapProperties;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        //1.处理异常
        //异常-收货地址为空
        AddressBook addressBook = addressBookMapper.getAddressById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //异常-如果超出配送范围
        //1.调用BaiduUtils工具类的获取坐标的方法,的到JSON格式的坐标
        //用户地址
        String userAddress = String.format("%s%s%s%s",
                addressBook.getProvinceName(),
                addressBook.getCityName(),
                addressBook.getDistrictName(),
                addressBook.getDetail());
        JSONObject userCoordinates = baiduMapUtil.getCoordinatesByAddress(userAddress);
        System.out.println(userCoordinates);
        //商家地址
        String provinceName = merchantAddress.getProvinceName();
        String cityName = merchantAddress.getCityName();
        String districtName = merchantAddress.getDistrictName();
        String detail = merchantAddress.getDetail();
        String merchantAddress = String.format("%s%s%s%s",
                provinceName,cityName,districtName,detail);

        JSONObject merchantCoordinates = baiduMapUtil.getCoordinatesByAddress(merchantAddress);
        //打印测试
        System.out.println(merchantCoordinates);
    /*    String url = baiduMapProperties.getGeocodingApi() + "?" +
                "address=" + URLEncoder.encode(address, "UTF-8") +
                "&output=json&ak=" + baiduMapProperties.getAk();
        System.out.println("Geocoding 请求URL：" + url);*/

        //2.取出来
        if (userCoordinates != null && merchantCoordinates != null) {
            Integer distance = baiduMapUtil.calculateRidingDistance(
                    merchantCoordinates.getDouble("lat"),
                    merchantCoordinates.getDouble("lng"),
                    userCoordinates.getDouble("lat"),
                    userCoordinates.getDouble("lng")
            );

            if (distance != null) {
                if (distance < 1000000000000000000l) {
                    System.out.println("配送距离：" + distance + "米，可配送");
                }else {
                    //超出配送范围异常
                    throw new OutOfDeliveryAreaException(MessageConstant.THE_ADDRESS_IS_OUT_OF_REACH);
                }
            } else {
                //无法测算距离异常
                throw new DistancesCannotBeCalculatedException(MessageConstant.DISTANCES_CANNOT_BE_CALCULATED);
            }
        } else {
            //地址解析失败,也抛出无法测算距离异常
            throw new DistancesCannotBeCalculatedException(MessageConstant.DISTANCES_CANNOT_BE_CALCULATED);
        }

        //异常-购物车为空
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart
                .builder()
                .userId(userId)
                .build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.getCart(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //2.构造订单数据orders


        Orders order = Orders.builder()
                .number(String.valueOf(System.currentTimeMillis()))//生成订单号?
                .status(Orders.TO_BE_CONFIRMED)
                .userId(userId)
                .orderTime(LocalDateTime.now())
                .payStatus(Orders.PAID)
                .phone(addressBook.getPhone())
                .address(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail())
                .consignee(addressBook.getConsignee())
                .build();
        BeanUtils.copyProperties(dto, order);
        User user = userMapper.getUserById(userId);
        if (user.getName() != null) {
            order.setUserName(user.getName());
        }
        orderMapper.insert(order);//会返回主键id

        //3.构造订单明细数据
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetails.add(orderDetail);
        }
        orderMapper.insertBatch(orderDetails);

        //4.删除购物车数据
        shoppingCartMapper.clean(userId);

        //5.封装要返回的数据
        OrderSubmitVO vo = new OrderSubmitVO()
                .builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        //推送消息到浏览器
        HashMap<Object, Object> map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",order.getId());
        map.put("content","订单号:"+order.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));


        return vo;
    }

    /**
     * 催单
     * @param orderId
     */
    @Override
    public void reminder(Integer orderId) {
        Orders order = orderMapper.getOrderById(orderId);

        //非空判断
        if (order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //推送消息到浏览器
        HashMap<Object, Object> map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",order.getId());
        map.put("content","订单号:"+order.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));

        //1.检查这个orderId是否存在且属于当前用户

        //2.使用Redis记录最后一次催单时间----设置合理的冷却时间（如5分钟）

        //调用商家服务接口通知--发送APP推送或短信通知--记录通知结果

        //保存催单记录到数据库----更新订单的最后催单时间
    }

    /**
     * 再来一单
     * @param orderId
     */
    @Transactional
    @Override
    public void oneMoreOrder(Long orderId) {
        //再来一单不应该是直接建立订单,而是把原来的订单详细数据再加入购物车
        List<OrderDetail> detailList = orderMapper.getOrderDetail(orderId);
        orderMapper.insertBatch(detailList);

/*        //1.根据订单id查询订单信息
        Orders oldOrder = orderMapper.getOrderById(orderId);
        //2.把旧订单的数据复制给新订单
        Orders order = new Orders();
        BeanUtils.copyProperties(oldOrder,order);*/

/*        //3.更新数据
        order.setId(null);
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(null);
        order.setPayStatus(Orders.UN_PAID);
        order.setCancelReason(null);
        order.setRejectionReason(null);
        order.setCancelTime(null);
        order.setEstimatedDeliveryTime(null);
        order.setDeliveryTime(null);
        //4.添加新订单
        orderMapper.insert(order);*/
    }

    /**
     * 取消订单
     * @param orderId
     */
    @Transactional
    @Override
    public void cancel(Integer orderId) {
        //修改这一条订单的状态
        orderMapper.cancel(orderId);

        //把订单明细表里的商品加到购物车中,然后把订单明细表中的数据删除
        List<OrderDetail> orderDetails = orderMapper.getOrderDetail(Long.valueOf(orderId));
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCarts.add(shoppingCart);
        }
        shoppingCartMapper.addCarts(shoppingCarts);
        //注意,这里不用删除订单明细表中的数据,因为取消后还需要查询
    }

    /**
     * 查看订单详情(查1条)
     * @param orderId
     */
    @Override
    public OrderVO getOrderById(Integer orderId) {
        Orders order = orderMapper.getOrderById(orderId);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        List<OrderDetail> detailList = orderMapper.getOrderDetail(order.getId());
        orderVO.setOrderDetailList(detailList);
        return orderVO;
    }

    /**
     * 查询订单详情(查多条)
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult getOrders(Integer page, Integer pageSize, Integer status) {
        //分页查询
        Long userId = BaseContext.getCurrentId();
        PageHelper.startPage(page, pageSize);
        //查订单表
        Page<Orders> orders = orderMapper.getOrders(userId, status);
        //再查订单详细数据
        ArrayList<OrderVO> orderVOS = new ArrayList<>();
        for (Orders order : orders) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            List<OrderDetail> detailList = orderMapper.getOrderDetail(order.getId());
            orderVO.setOrderDetailList(detailList);
            orderVOS.add(orderVO);
        }

        return new PageResult(orders.getTotal(), orderVOS);
    }

    /**
     * 用户订单支付
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        //getById()需要自己实现
        User user = userMapper.getUserById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

}









